#! /usr/bin/perl -w
#------------------------------------------------
# Author:    kasula
# Created:   Mon Oct 24 22:58:56 PDT 2011
# File Name: Tabulate
# USAGE: 
#       Tabulate [-d <Delimiter>] -r <RowIdField> -c <ColIdField> -f <File>
# 
# 
#------------------------------------------------
use Getopt::Long ;

$Delimiter = " ";
$result = GetOptions (
        "d=s" => \$Delimiter,
        "f=s" => \$File,
        "r=i" => \$RowIdField,
        "c=i" => \$ColIdField,
        "h"   => \$help
);

if ($help) { system "grep -m 1 -A 2 USAGE $0"; exit; }
die "ERROR: GetOptions failed...\n"                     if ( not $result );
die "ERROR: Require a file to process\n"                if ( not defined $File );
die "ERROR: Require a Row Identifier Field\n"           if ( not defined $RowIdField);
die "ERROR: Require a Column Identifier Field\n"        if ( not defined $ColIdField);

open IFH, "<$File" or die "FATAL: Opening $File failed...\n";
while ( <IFH> ) {
        chomp ;
        @Fields = split $Delimiter ;
        $Row{$Fields[$RowIdField]}++;
        $Col{$Fields[$ColIdField]}++;
        $Cnt{$Fields[$RowIdField].$Delimiter.$Fields[$ColIdField]}++;
}
close IFH;

print "-,";
while (($kCol,$vCol) = each %Col) { print "$kCol,"; }
print "Tot,\n";

while (($kRow,$vRow) = each %Row) {
        print "$kRow,";
        while (($kCol,$vCol) = each %Col) {
                if ( exists $Cnt{$kRow.$Delimiter.$kCol} ) { printf "%d,", $Cnt{$kRow.$Delimiter.$kCol}; }
                else { printf "0,"; }
        }
        print "$vRow,\n";
}

$GTot = 0;
print "Tot,";
while (($kCol,$vCol) = each %Col) { print "$vCol,"; $GTot += $vCol; }
print "$GTot,\n";
